<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\common;
use think\facade\Db;
class Coupon
{
	//发送优惠券 $checktj:是否检测领取条件
	public static function send($aid,$mid,$cpid,$checktj=false,$tr_roomId=0){
		$coupon = db('coupon')->where('aid',$aid)->where('id',$cpid)->find();
		if(!$coupon) return ['status'=>0,'msg'=>t('优惠券').'不存在'];
		if($coupon['stock']<=0) return ['status'=>0,'msg'=>'库存不足'];
		if($checktj){
			$gettj = explode(',',$coupon['gettj']);
			$member = Db::name('member')->where('id',$mid)->find();
			if(!in_array('-1',$gettj) && !in_array($member['levelid'],$gettj)){ //不是所有人
				if(in_array('0',$gettj)){ //关注用户才能领
					if($member['subscribe']!=1){
						$appinfo = \app\common\System::appinfo($aid,'mp');
						return ['status'=>0,'msg'=>'请先关注'.$appinfo['nickname'].'公众号'];
					}
				}else{
					if(count($gettj)==1){
						$levelname = Db::name('member_level')->where('id',$gettj[0])->value('name');
						return ['status'=>0,'msg'=>'只有'.$levelname.'才能领取'];
					}
					return ['status'=>0,'msg'=>'您没有领取权限'];
				}
			}
		}
		$data = [];
		$data['aid'] = $aid;
		$data['bid'] = $coupon['bid'];
		$data['mid'] = $mid;
		$data['couponid'] = $coupon['id'];
		$data['couponname'] = $coupon['name'];
		$data['money'] = $coupon['money'];
		$data['discount'] = $coupon['discount'];
		$data['minprice'] = $coupon['minprice'];
		if($coupon['yxqtype'] == 1){
		    //固定有效期
			$yxqtime = explode(' ~ ',$coupon['yxqtime']);
			$data['starttime'] = strtotime($yxqtime[0]);
			$data['endtime'] = strtotime($yxqtime[1]);
		}elseif($coupon['yxqtype'] == 2){
		    //领取后x天有效
            $data['starttime'] = time();
            $data['endtime'] = $data['starttime'] + 86400 * $coupon['yxqdate'];
        }elseif($coupon['yxqtype'] == 3){
		    //次日起计算有效期
			$data['starttime'] = strtotime(date('Y-m-d')) + 86400;
			$data['endtime'] = $data['starttime'] + 86400 * $coupon['yxqdate'] - 1;
		}
		$data['type'] = $coupon['type'];
		$data['limit_count'] = $coupon['limit_count'];
		$data['limit_perday'] = $coupon['limit_perday'];
		$data['createtime'] = time();
		$data['code'] = random(16);
		$data['hexiaoqr'] = createqrcode(m_url('admin/hexiao/hexiao?type=coupon&co='.$data['code'], $aid));
		db('coupon_record')->insert($data);
		db('coupon')->where('aid',$aid)->where('id',$coupon['id'])->update(['stock'=>Db::raw('stock-1'),'getnum'=>Db::raw('getnum+1')]);
		Wechat::updatemembercard($aid,$mid);
		return ['status'=>1,'msg'=>'发送成功'];
	}
	//支付后送券
	public static function getpaygive($aid,$mid,$type,$money,$orderids=null){
		if(!$money) $money = 0;
		$time = time();
		$whereOr = [];
		if($type == 'shop' && $orderids){
			if(!is_array($orderids)){
				$orderids = [$orderids];
			}
			$proids = db('shop_order_goods')->where('orderid','in',$orderids)->column('proid');
			foreach($proids as $proid){
				$whereOr[] = "find_in_set('{$proid}',buyproids)";
			}
		}
		$whereOr = implode(' or ',$whereOr);
		if($whereOr){
			$whereOr = "buyprogive=1 and ({$whereOr})";
		}else{
			$whereOr = '1=0';
		}
		$couponlist = db('coupon')->where("aid={$aid} and unix_timestamp(starttime)<={$time} and unix_timestamp(endtime)>={$time} and stock>0")->where("(paygive=1 and paygive_minprice<={$money} and paygive_maxprice>={$money} and find_in_set('{$type}',paygive_scene)) or ($whereOr)")->order('sort desc,id desc')->select()->toArray();
		//var_dump(Db::getlastsql());
		foreach($couponlist as $k=>$coupon){
			$havegetnum = db('coupon_record')->where('aid',$aid)->where('mid',$mid)->where('couponid',$coupon['id'])->count();
			if($havegetnum >= $coupon['perlimit']) unset($couponlist[$k]);
		}
		if(!$couponlist) return false;
		
		foreach($couponlist as $k=>$coupon){
			$thisnum = 0;
			if($coupon['paygive']==1 && $coupon['paygive_minprice'] <= $money && $coupon['paygive_maxprice'] >= $money && in_array($type,explode(',',$coupon['paygive_scene']))){
				$thisnum++;
			}
			if($type == 'shop' && $orderids && $coupon['buyprogive'] == 1){
				$coupon['buyproids'] = explode(',',$coupon['buyproids']);
				$coupon['buypro_give_num'] = explode(',',$coupon['buypro_give_num']);
				foreach($coupon['buyproids'] as $k2 => $proid) {
					if(in_array($proid, $proids) && $coupon['buypro_give_num'][$k2] > 0) {
						$thisnum += $coupon['buypro_give_num'][$k2];
					}
				}
			}
			$couponlist[$k]['givenum'] = $thisnum;
		}

		return $couponlist;
	}

    //使用优惠券

    /**
     * @param $aid
     * @param $coupon_record_id
     * @param $usecoupon_type 1付款后，2确认收货,hexiao
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function useCoupon($aid,$coupon_record_id,$usecoupon_type=1){
        if(getcustom('usecoupon_give_score') || getcustom('usecoupon_give_coupon') || getcustom('usecoupon_give_money')){

            //该优惠券是不是赠送的
            $crecord = Db::name('coupon_record')->where('id',$coupon_record_id)->find();
            if($crecord['from_mid']){
                //是不是满足条件
                $coupon = Db::name('coupon')->where('id',$crecord['couponid'])->find();
                if($coupon && ($coupon['usecoupon_give_type']==$usecoupon_type || $usecoupon_type=='hexiao')){
                    if($coupon['usecoupon_give_score']>0 && getcustom('usecoupon_give_score')){
                        \app\common\Member::addscore($aid,$crecord['from_mid'],$coupon['usecoupon_give_score'],'转赠'.t('优惠券').'被使用赠送'.t('积分'));
                    }
                    if($coupon['usecoupon_give_coupon'] && getcustom('usecoupon_give_coupon')){
                        $coupon_ids = explode(',', $coupon['usecoupon_give_coupon']);
                        if($coupon_ids) {
                            foreach ($coupon_ids as $coupon_id) {
                                \app\common\Coupon::send($aid, $crecord['from_mid'], $coupon_id);
                            }
                        }
                    }
                    if($coupon['usecoupon_give_money']>0 && getcustom('usecoupon_give_money')){
                        \app\common\Member::addmoney($aid,$crecord['from_mid'],$coupon['usecoupon_give_money'],'转赠'.t('优惠券').'被使用赠送'.t('余额'));
                    }
                }
            }
        }
    }
}